import time
import datetime
import requests
import json
from IPProxyPool.settings import TEST_TIMEOUT
from IPProxyPool.utils.http import get_request_headers
from IPProxyPool.utils.log import logger
from IPProxyPool.domain import Proxy


def check_proxy(proxy):
    '''
    检测代理协议类型, 匿名程度
        :param
        :return:(协议: http和https:2,https:1,http:0, 匿名程度:高匿:0,匿名: 1, 透明:0 , 速度, 单位s )
    '''

    # 准备代理数据
    proxies = {
        'http': 'http://{}:{}'.format(proxy.ip, proxy.port),
        'https': 'https://{}:{}'.format(proxy.ip, proxy.port),
    }

    # 测试代理
    http, http_nick_type, http_speed = _check_http_proxies(proxies)
    https, https_nick_type, https_speed = _check_http_proxies(proxies, False)

    # 添加修改时间和存活时间
    last_tested_time = datetime.datetime.strptime(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
                                                  '%Y-%m-%d %H:%M:%S')
    proxy.last_tested_time = last_tested_time.strftime('%Y-%m-%d %H:%M:%S')
    create_time = datetime.datetime.strptime(proxy.create_time, '%Y-%m-%d %H:%M:%S')

    survived_hours = (last_tested_time - create_time).days * 24 + (
            last_tested_time - create_time).seconds / 3600  # 时间差（小时）

    # http0,https1,http&https2
    if http and https:
        proxy.protocol = 2
        proxy.nick_type = http_nick_type
        proxy.speed = http_speed
        proxy.survived_hours = round(survived_hours, 2)
    elif http:
        proxy.protocol = 0
        proxy.nick_type = http_nick_type
        proxy.speed = http_speed
        proxy.survived_hours = round(survived_hours, 2)
    elif https:
        proxy.protocol = 1
        proxy.nick_type = https_nick_type
        proxy.speed = https_speed
        proxy.survived_hours = round(survived_hours, 2)
    else:
        proxy.protocol = -1
        proxy.nick_type = -1
        proxy.speed = -1
        proxy.survived_hours = -1

    return proxy


# 检查代理IP速度 和 匿名程度;
# 代理IP速度: 就是发送请求到获取响应的时间间隔
# 匿名程度检查:
# 对 http://httpbin.org/get 或 https://httpbin.org/get 发送请求
# 如果 origin 中有','分割的两个IP就是透明代理IP
# 如果 headers 中包含 Proxy-Connection 说明是匿名代理IP
# 否则就是高匿代理IP
# 检查代理IP协议类型
# 如果 http://httpbin.org/get 发送请求可以成功, 说明支持http协议
# 如果 https://httpbin.org/get 发送请求可以成功, 说明支持https协议

def _check_http_proxies(proxies, is_http=True):
    # 匿名类型：0高匿 1匿名 2透明
    nick_type = -1
    # 响应速度
    spped = -1

    if is_http:
        test_url = 'http://httpbin.org/get'
    else:
        test_url = 'https://httpbin.org/get'

    try:

        # 开始记录时间
        start = time.time()
        res = requests.get(test_url, headers=get_request_headers(), proxies=proxies, timeout=TEST_TIMEOUT, verify=False)
        if res.ok:
            # 计算速度
            speed = round(time.time() - start, 2)
            # 判断匿名程度
            header_dict = json.loads(res.text)
            origin = header_dict['origin']
            proxy_connection = header_dict['headers'].get('Proxy-Connection', None)
            if ',' in origin:
                nick_type = 2  # 透明
            elif proxy_connection:
                nick_type = 1  # 匿名
            else:
                nick_type = 0  # 高匿

            return True, nick_type, speed
        return False, nick_type, spped
    except Exception as e:
        return False, nick_type, spped


if __name__ == '__main__':
    proxy = Proxy('60.205.158.246', '3128')
    print(check_proxy(proxy))
